<template>
  <div class="register">
    <nav>
      <div class="box">
        <van-icon name="arrow-left" class="icon icon-left" @click="gotosignin" />
        <span>注册</span>
      </div>
    </nav>
    <div class="header">
      <div class="left">
        <span>欢迎注册</span>
        <p>乐淘一番</p>
      </div>
      <div class="right">
        <img src="https://mall.leyifan.com/static/h5/new_images/register_bg.png" alt="" />
      </div>
    </div>
    <div class="c-form">
      <div class="form">
        <p>手机号码</p>
        <input v-model="newUsername" placeholder="请填写手机号码！" @input="validatePhone" />
        <div class="error-message" v-if="phoneError">{{ phoneError }}</div>
      </div>
      <div class="form">
        <p>设置密码</p>
        <input
          v-model="newPassword"
          placeholder="密码规则为6-18位字母加数字"
          @input="validatePassword"
        />
        <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
      </div>
      <div class="form yym">
        <p>验证码</p>
        <input placeholder="请填写验证码!" v-model="userVerificationCode" />
        <span class="t-yym" style="color: #ff3d58" @click="generateVerificationCode"
          >获取验证码</span
        >
      </div>
      <div class="form">
        <p>确认密码</p>
        <input v-model="confirmPassword" placeholder="请填写确认密码!" />
      </div>
      <div class="form m20">
        <p>电子邮箱</p>
        <input v-model="email" placeholder="请填写电子邮件!" @input="validateEmail" />
        <div v-if="emailError" class="error-message">{{ emailError }}</div>
      </div>
      <button @click="register()">立即注册</button>
    </div>
    <div class="footer">
      <van-checkbox v-model="checked" checked-color="#ee0a24" icon-size="14rem"></van-checkbox>
      <span style="margin-left: 10rem">已阅读并同意</span>
      <span style="color: #ff3d58">《用户协议》</span>及
      <span style="color: #ff3d58">《隐私政策》</span>
    </div>

    <br />
    <br />
    <br />
    <br />
    <br />
  </div>
</template>

<script setup lang="ts">
import { ref, createApp } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/useUserStore'

const userStore = useUserStore()
// 钩子函数获取路由实例
const router = useRouter()
const newUsername = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const email = ref('')
const phoneError = ref('')
const emailError = ref('')
const checked = ref(false)
const passwordError = ref('')
// 中国大陆手机号码正则表达式
const phoneRegex = /^1[3-9]\d{9}$/
// 电子邮箱正则表达式
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
// 密码正则表达式
const passwordRegex = /^(?=.*\d)(?=.*[a-zA-Z]).{6,18}$/
const verificationCode = ref('') // 存储生成的验证码
const userVerificationCode = ref('') // 用户输入的验证码

const generateVerificationCode = () => {
  const code = Math.floor(1000 + Math.random() * 9000).toString()
  verificationCode.value = code
  showToast(`验证码为: ${code}`) // 这里可以改为发送到手机或其他方式
}
const validatePhone = () => {
  if (!phoneRegex.test(newUsername.value)) {
    phoneError.value = '请输入有效的手机号码'
  } else {
    phoneError.value = ''
  }
}

const validateEmail = () => {
  if (!emailRegex.test(email.value)) {
    emailError.value = '请输入有效的电子邮箱'
  } else {
    emailError.value = ''
  }
}
const validatePassword = () => {
  if (!passwordRegex.test(newPassword.value)) {
    passwordError.value = '密码必须为6-18位字母加数字'
  } else {
    passwordError.value = ''
  }
}
const register = () => {
  if (!checked.value) {
    showToast('请阅读并同意《用户协议》及《隐私政策》')
    return
  }
  if (newPassword.value !== confirmPassword.value) {
    showToast('两次输入的密码不一致')
    return
  }
  if (passwordError.value) {
    showToast('请检查密码的格式')
    return
  }
  if (userVerificationCode.value !== verificationCode.value) {
    showToast('验证码错误')
    return
  }
  if (email.value === '') {
    // 所有验证通过，可以进行注册操作
    showToast('邮箱不能为空!!!')
    return
  }

  // 获取当前存储的所有用户信息
  const usersString = localStorage.getItem('users')
  let users = usersString ? JSON.parse(usersString) : []

  // 检查用户名是否已存在
  const userExists = users.some((user) => user.username === newUsername.value)
  if (userExists) {
    showToast('该手机号码已被注册')
    return
  }

  // 生成用户ID
  const userId = Math.floor(1000000 + Math.random() * 9000000).toString()

  // 添加新用户信息到数组
  users.push({
    id: userId,
    username: newUsername.value,
    password: newPassword.value,
    email: email.value,
  })

  // 保存用户信息到本地存储
  localStorage.setItem('users', JSON.stringify(users))
  showToast('注册成功')
  userStore.login(userId, newUsername.value, email.value)

  // 跳转到登录页面
  router.replace({ path: '/login' })
}
const gotosignin = () => {
  router.replace({ path: '/login' })
}
</script>

<style lang="less" scoped>
.register {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  padding: 40rem 0;
  nav {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    .box {
      width: 100vw;
      height: 40rem;
      background-color: #fff;
      font-size: 18rem;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .icon-left {
        position: absolute;
        top: 12rem;
        left: 14rem;
      }
      span {
        line-height: 40rem;
        font-size: 16rem;
        font-weight: bold;
      }
    }
  }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rem 24rem;

    .left {
      display: flex;
      flex-direction: column;
      justify-content: center;
      span {
        font-size: 16rem;
        font-weight: 400;
        margin-bottom: 10rem;
        line-height: 16rem;
      }
      p {
        font-size: 28rem;
        font-weight: 700;
        line-height: 28rem;
      }
    }
    .right {
      img {
        width: 83rem;
        height: 70rem;
        display: block;
      }
    }
  }
  .c-form {
    // padding: 0 10rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .form {
      padding: 10rem 14rem;
      .error-message {
        position: absolute;
        color: red;
        font-size: 12rem;
        left: 35rem;
      }
      p {
        font-size: 12rem;
        color: #333;
        margin-bottom: 10rem;
        line-height: 12rem;
      }
      input {
        width: 327rem;
        height: 42rem;
        padding: 0 14rem;
        border-radius: 8rem;
        font-size: 12rem !important;
        background-color: #f5f5f5;
        outline: none;
        border: none;
      }
    }
    button {
      width: 330rem;
      height: 48rem;
      text-align: center;
      border-radius: 24rem;
      font-size: 16rem;
      font-weight: 500;
      border: none;
      line-height: 48rem;
    }
    .m20 {
      margin-bottom: 20rem;
    }
    .yym {
      position: relative;
      .t-yym {
        display: block;
        position: absolute;
        top: 50%;
        right: 28rem;
        font-size: 12rem;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: space-start;
    align-items: center;
    padding-left: 25rem;
    margin: 20rem 0;
    span {
      font-size: 14rem;
    }
    .red {
      color: #ff3d58;
    }
  }
}
</style>